const Service = require('egg').Service

class bannerService extends Service {
  get File() {
    return this.ctx.model.File
  }
  
  // 插入banner
  async insert(data) {
    const _data = await new this.File(data)
    _data.save()
    return _data
  }

  // 查询banner
  async getList() {
    const ret = await this.File.find({type: 2},null,{
      sort: {
        sortNum: -1
      }
    }).populate('img','link')
    return {
      list: ret
    }
  }


  // 删除banner
  async delete(id) {
    const { ctx,service } = this
    const _data = await this.File.findById(id)
    if(!_data) {
      ctx.throw('_id不正确！')
    }
    _data.remove()
    // 删除文件
    await ctx.model.File.deleteOne({_id: _data._id})
    service.toolService.deleteDiskFile(_data.link)
    return {
      code: 200,
      message: '删除成功'
    }
  }

  // 修改banner
  async update(body) {
    const { ctx } = this
    //查找banner
    const _data = await this.File.findByIdAndUpdate(body.id,Object.assign(body,{updatedAt: Date.now()})) 
    if(!_data) {
      ctx.throw(422,'_id不正确！')
    }
    return {
      code: 200,
      message: '修改成功'
    }
  }
  
}

module.exports = bannerService